<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\BaseController;
use App\Http\Controllers\Controller;
use App\Http\Controllers\utils\Common;
use App\Models\Api\User;
use App\Models\Api\UserImg;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Tymon\JWTAuth\Facades\JWTAuth;
// 图片处理
use Intervention\Image\ImageManager;
use Intervention\Image\Encoders\AutoEncoder;

use Intervention\Image\Drivers\Gd\Driver;

class UserController extends BaseController
{
    function __construct()
    {
        $this->common = new Common();
    }
    /**
     * 登陆
     */
    public function login(Request $request)
    {
        try {
            $params = $request->all();
            $account = isset($params['account']) ? $params['account'] : '';
            $password = isset($params['password']) ? $params['password'] : '';

            $validator = Validator::make($params, [
                'account' => 'required',
                'password' => 'required'
            ]);

            if ($validator->fails()) {
                return $this->responseData([], $validator->errors(), 400);
            }
            $user = User::where($this->checkStrType($account), $account)->where('password', $password)->first();

            if (!$user) {
                return $this->responseData([], '登陆失败 账号或密码错误', 400);
            }
            if (intval($user->status) == -1) {
                return $this->responseData([], '登陆失败 ' . $account . '已被禁用,可联系chengxuyuan_xiaoq@163.com解除禁用', 400);
            }
            // 生成token
            $token = JWTAuth::fromUser($user);

            $data = [
                "userinfo" => $user,
                "token" => $token
            ];
            return $this->responseData($data, '登陆成功', 200);
            // return $this->responseData($user, '登陆成功', 200);
        } catch (\Throwable $th) {
            $errorInfo = isset($th->errorInfo) ? $th->errorInfo : "这是一个html $th";
            $this->error_log(__FILE__, __LINE__, json_encode($errorInfo));
            return  $this->responseData($th, '系统错误', 400);
        }
    }

    /**
     * 注册
     */
    public function register(Request $request)
    {
        try {
            $params = $request->all();
            $validator = Validator::make($params, [
                'name' => 'required',
                'phone' => ['required', 'regex:/^1[3456789]\d{9}$/'],
                'email' => 'required|email',
                'password' => 'required|min:6'
            ]);

            if ($validator->fails()) {
                return $this->responseData([], $validator->errors(), 400);
            }

            $params['createtime'] = now();
            $params['status'] = 1;
            $params['avatar'] = 'api/v1/user/default';

            // $phoneSelect = User::where('phone', '=', $params['phone'])->get();
            // $emailSelect = User::where('email', '=', $params['email'])->get();
            // if (!$phoneSelect->isEmpty()) {
            //     return $this->responseData([], '手机号已经注册', 400);
            // }

            // if (!$emailSelect->isEmpty()) {
            //     return $this->responseData([], '邮箱已经注册', 400);
            // }

            if ($this->dataExists(User::class, 'phone', $params['phone'])) {
                return $this->responseData([], '手机号已经注册', 400);
            }

            if ($this->dataExists(User::class, 'email', $params['email'])) {
                return $this->responseData([], '邮箱已经注册', 400);
            }

            if (User::create($params)) {
                return $this->responseData([], '注册成功', 200);
            } else {
                return $this->responseData([], '注册失败', 200);
            }
        } catch (\Throwable $th) {
            $errorInfo = isset($th->errorInfo) ? $th->errorInfo : "这是一个html $th";
            $this->error_log(__FILE__, __LINE__, json_encode($errorInfo));
            return  $this->responseData($th, '系统错误', 400);
        }
    }

    /**
     * 编辑
     */
    public function edit(Request $request, string $id)
    {
        $params = $request->all();
        if ($params['column'] == 'phone' || $params['column'] == 'email') {
            $waitValidate = [
                $params['column'] => $params['value']
            ];
            $validationRule = [
                'phone' => ['required', 'regex:/^1[3456789]\d{9}$/'],
                'email' => 'required|email',
            ];
            $validator = Validator::make($waitValidate, [
                $params['column'] =>  $validationRule[$params['column']]
            ]);

            if ($validator->fails()) {
                return $this->responseData([], $validator->errors(), 400);
            }

            $user = User::where($params['column'], $params['value'])->first();
            if ($user)
                if (intval($user->status) == -1) {
                    // 更新记录的属性
                    $user[$params['column']] = '';
                    // 保存更新
                    $user->save();
                } else
                    return $this->responseData([], $params['value'] . "已经注册了", 400);
        }


        return $this->common->apiEdit(User::class, $request, $id);
    }

    /**
     * 删除
     */
    public function del(Request $request, string $id)
    {
        return $this->common->apiDelete(User::class, $request, $id);
    }

    /**
     * 物理删除
     */
    public function physicalDel(string $id)
    {
        $user = User::find($id);
        if (!$user) {
            return $this->responseData([], '数据不存在', 400);
        }
        $user->delete();
        return $this->responseData([], '用户已彻底删除', 200);
    }

    /**
     * 默认头像
     */
    public function default()
    {
        // 获取文件路径
        $filePath = storage_path('app/gg_exam_img/' . 'default.png');
        // 检查文件是否存在
        if (file_exists($filePath)) {
            //压缩
            $manager = new ImageManager(new Driver());
            // 打开图片
            $image = $manager->read($filePath);
            $encoded = $image->encode(new AutoEncoder(quality: 20));
            // 获取文件的 MIME 类型
            $mimeType = mime_content_type($filePath);

            // 构建响应 file_get_contents($filePath)
            $response = Response::make($encoded, 200);
            $response->header("Content-Type", $mimeType);

            // 返回响应
            return $response;
        } else {
            return  $this->responseData([], '文件不存在', 400);
        }
    }

    /**
     * 获取用户头像
     */
    public function avatar($id)
    {
        $data = UserImg::where('userid', $id)->first();
        if (!$data) {
            return $this->responseData([], '此用户暂未上传头像', 400);
        }
        $avatarPath = storage_path("app/gg_exam_img/avatar/$id/$data->filename");
        if (file_exists($avatarPath)) {
            //压缩
            $manager = new ImageManager(new Driver());
            // 打开图片
            $image = $manager->read($avatarPath);
            $encoded = $image->encode(new AutoEncoder(quality: 20));
            // 获取文件的 MIME 类型
            $mimeType = mime_content_type($avatarPath);

            // 构建响应 file_get_contents($avatarPath)
            $response = Response::make($encoded, 200);
            $response->header("Content-Type", $mimeType);

            // 返回响应
            return $response;
        } else {
            return  $this->responseData([], '文件不存在', 400);
        }
    }

    /**
     * 头像上传
     */
    public function upload(Request $request, $id)
    {
        try {
            $params = $request->all();
            // $userid = isset($params['userid']) ? $params['userid'] : 0;
            $userid = $id;
            if ($request->hasFile('avatar') && $request->file('avatar')->isValid()) {
                $fileName = time() . $request->file('avatar')->getClientOriginalName();;
                $fileSize = $request->file('avatar')->getSize();
                $filePath = $request->file('avatar')->storeAs("gg_exam_img/avatar/$userid", $fileName);

                // $request->file('file')->store("./uploads", md5(time() . rand(100000, 999999)));
                // 更新 user_img 表
                $imgData = UserImg::where('userid', $userid)->first();
                if ($imgData) {
                    $prePath = storage_path("app/gg_exam_img/avatar/{$userid}/{$imgData->filename}");
                    if (file_exists($prePath)) {
                        unlink($prePath);
                        Log::channel('updateInfo')->info("id: $userid 用户更新了头像");
                    }
                    $imgData->filename = $fileName;
                    $imgData->save();
                } else {
                    $insertRes = UserImg::create(['filename' => $fileName, 'createtime' => now(), 'userid' => $userid]);
                    User::where('id', $userid)->update(['avatar' => "api/v1/user/avatar/$userid"]);
                    if ($insertRes) {
                        return $this->responseData([], '头像上传成功', 200);
                    }
                    return $this->responseData([], "头像上传失败", 400);
                }
                return $this->responseData([], "文件上传成功，文件路径:$filePath ,$fileSize: 字节", 200);
            } else {
                return $this->responseData([], "文件上传失败", 400);
            }
        } catch (\Throwable $th) {
            $errorInfo = isset($th->errorInfo) ? $th->errorInfo : "这是一个html $th";
            $this->error_log(__FILE__, __LINE__, json_encode($errorInfo));
            return  $this->responseData($th, '系统错误', 400);
        }
    }

    /**
     * 根据token 解析用户信息返回给前端
     */
    public function token()
    {
        try {
            $headers  = request()->header();
            $token = str_replace("Bearer ", "", $headers['authorization'])[0];

            $payload = JWTAuth::setToken($token)->getPayload();
            // 获取解析后的数据
            $userid = $payload->toArray()['id'];
            $user = User::where('id', $userid)->first();
            return $this->responseData($user, "解析成功", 400);
        } catch (\Tymon\JWTAuth\Exceptions\TokenExpiredException $e) {
            // 处理令牌过期异常
            return  $this->responseData(["errorInfo" => "token过期"], 'token错误', 400);
        } catch (\Tymon\JWTAuth\Exceptions\TokenInvalidException $e) {
            // 处理无效令牌异常
            return  $this->responseData(["errorInfo" => "token无效"], 'token错误', 400);
        } catch (\Tymon\JWTAuth\Exceptions\JWTException $e) {
            // 处理其他 JWT 异常
            echo "JWT Exception";
            return  $this->responseData(["errorInfo" => "其他JWT未知错误"], 'token错误', 400);
        } catch (\Throwable $th) {
            $errorInfo = isset($th->errorInfo) ? $th->errorInfo : "这是一个html $th";
            $this->error_log(__FILE__, __LINE__, json_encode($errorInfo));
            return  $this->responseData($th, '系统错误', 400);
        }
    }

    /**
     * 检测账号相关字段是否以及注册 phone email
     */
    public function check(Request $request)
    {
        try {
            $params = $request->all();
            $account = isset($params['account']) ? $params['account'] : '';

            $valid = $this->checkStrType($account) == 'email' ? 'required|email' : [
                'required',
                'regex:/^[0-9]{11}$|^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/',
            ];

            $validator = Validator::make($params, [
                'account' => $valid,
            ]);
            if ($validator->fails()) {
                return $this->responseData([], $validator->errors(), 400);
            }
            $user = User::where($this->checkStrType($account), $account)->first();
            if ($user) {
                $text = "这个" . $this->checkStrType($account) . "已经注册";
                return $this->responseData([], $text, 400);
            }
            return $this->responseData([], 'ok', 200);
        } catch (\Throwable $th) {
            $errorInfo = isset($th->errorInfo) ? $th->errorInfo : "这是一个html $th";
            $this->error_log(__FILE__, __LINE__, json_encode($errorInfo));
            return  $this->responseData($th, '系统错误', 400);
        }
    }
}
